﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using DocManagerORM.ORM;
using DocManagerControls.CLASSI;
using DS2171Utils;
using System.IO;
using DocManagerORM.Caching;

namespace DocManagerControls.Controls
{
    /// <summary>
    /// Interaction logic for RicercaDocControl.xaml
    /// </summary>
    public partial class RicercaDocControl : BaseCusControl
    {
        Dictionary<int, string[]> m_dictSottoCat = new Dictionary<int, string[]>();
        Lazy<Encryptor> m_Encryptor = new Lazy<Encryptor>(() => { return new Encryptor(); });
        Lazy<ZipDati> m_ZipDati = new Lazy<ZipDati>(() => { return new ZipDati(); });

       
        QueryDoc m_QueryDoc = new QueryDoc();

        public RicercaDocControl()
        {
            InitializeComponent();  
            CaricaDatiVari();
            txtNomeDoc.Focus();  

            //addMenuHandler((e) => {

            //    switch (e)
            //    { 
            //        case "exit":
            //            MessageBox.Show("handler ok");  
            //            break;
            //    }

            //    ; }); 



        }

        private void CaricaDatiVari()
        {
            CacheBase.BindaComboBoxdata<Categorie>(ref comboCategorie, "Categorie", "ID", "Categoria");  
        }//fM

        private void showPDF(string pFile)
        {
            Process process = new Process();
            process.StartInfo.Verb = "Open"; //"PrintTo";

            process.StartInfo.FileName = @"C:\Program Files\Adobe\Reader 9.0\Reader\acrord32.exe";

            process.StartInfo.Arguments = string.Format(" \"{0}\" ", pFile); //   /t

            process.StartInfo.RedirectStandardOutput = false;
            process.StartInfo.CreateNoWindow = true;

            process.StartInfo.UseShellExecute = false;

            process.Start();

            //process.StandardOutput.ReadToEnd();

            process.WaitForExit();

        }//fm


        protected void btnCerca_Click(object sender, RoutedEventArgs e)
        {
            CercaDoc();

        }//fm

        private void CercaDoc()
        {
            string docName = string.Empty;
            int catID , sottoCatID , tagsID;
            int? catIDnull=null , sottoCatIDnull=null, tagsIDnull=null;
            
            try
            {

                if (!string.IsNullOrEmpty(txtNomeDoc.Text))
                {
                    docName = txtNomeDoc.Text;
                }
                else
                {
                    if (comboCategorie.SelectedValue != null)
                    {   int.TryParse(comboCategorie.SelectedValue.ToString(), out catID);
                        catIDnull = catID ;
                    }
                    
                    if (comboSottoCategorie.SelectedValue != null)
                    {
                        int.TryParse(comboSottoCategorie.SelectedValue.ToString(), out sottoCatID);
                        sottoCatIDnull = sottoCatID ;
                    }
                }

                if (comboTagsPredefiniti.SelectedValue != null)
                    {
                        int.TryParse(comboTagsPredefiniti.SelectedValue.ToString(), out tagsID);
                        tagsIDnull = tagsID;
                    }
                 

                var tagsPersonali = txtTagsPersonalizzati.Text.Trim();   

                //Preleva la VISTA dei documenti <<<<<<<<<<
                var arrDocs = new QueryDoc().prelevaDocView(docName,checkBoxIsID.IsChecked.Value, catIDnull, sottoCatIDnull,
                   tagsIDnull,tagsPersonali ).ToArray();

                listDocs.ItemsSource = arrDocs;

                var totDocs = 0;
                totDocs = arrDocs == null ? 0 : arrDocs.Length;

                lblMessaggi.Content = string.Format("{0} documenti prelevati ( {1}", totDocs, DateTime.Now.ToLongTimeString());

            }
            catch (Exception ex)
            {
                lblMessaggi.Content = "Errore : Documento non modificato ( " + ex.Message;
            }
        }


        private void comboCategorie_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var cat = comboCategorie.SelectedItem as Categorie;
            if (cat == null) return;
            
            CacheBase.BindaComboBoxdata<SottoCategorie>(ref comboSottoCategorie, "SottoCategorie", "ID",
                "Categoria", cat.ID);  
        }


        private void listDocs_Selected(object sender, RoutedEventArgs e)
        {
            
        }//fM
               

        private void listDocs_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var item = e.OriginalSource as Image;
            if (item == null) return;

            int idDoc = 0;
            if (!int.TryParse(item.Tag.ToString(), out idDoc)) return;

            var doc = m_QueryDoc.prelevaDoc(idDoc).FirstOrDefault();

            var dir = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Documenti");
            
            if (!System.IO.Directory.Exists(dir)) System.IO.Directory.CreateDirectory(dir);
            var filePath = System.IO.Path.Combine(dir, doc.FileName);

            DocUtils.SaveBytesInFile(filePath, doc.Documento);
            DocUtils.showDoc(filePath);

        }

        private void txtNomeDoc_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
            {
                CercaDoc();
                e.Handled = true;
            }
        }//fM

        private void contMenu_Click(object sender, RoutedEventArgs e)
        {
            var lst =contMenu.PlacementTarget as ListView;
            var selDoc = lst.SelectedItem as vwDocumenti;//documento
            if (selDoc == null) return;

            var comando = ((MenuItem)e.Source).Header.ToString().ToLower();
            switch (comando)
            {
                case "vedi":
                    vediDocumento(selDoc);
                    break;
                case "read":

                    break;
                case "modifica":

                    break;
                case "download":

                    break;
                case "delete":

                    break;
                case "avvia iter":
                    CreaWFControl iter = new CreaWFControl(selDoc.ID,selDoc.FileName);
                    getFrameContainer().Content = iter;
                    break;
                default:
                    break;
            }

        }

        private void vediDocumento(vwDocumenti selDoc)
        {
            prelevaDoc(selDoc);          
        }



        private void btnVediDoc_Click(object sender, RoutedEventArgs e)
        {

        }//fM

        //preleva ed eventualmente decomprime il documento
        public void prelevaDoc(vwDocumenti pSelDoc)
        {
            var doc = m_QueryDoc.prelevaDoc(pSelDoc.ID).FirstOrDefault();

            var tempDir = System.IO.Path.Combine(Environment.CurrentDirectory,"TempFiles",doc.FileName);

            byte[] arrBytes = doc.Documento;

            int lunghezzaOriginaria = 0 ;//doc todo <<<<<<<<<<<<<<<<<<<<<<<<<< <<<<


            if (doc.IsZipped.GetValueOrDefault() || doc.FileName.Contains(".gz"))
            {
                var path = System.IO.Path.Combine(Environment.CurrentDirectory, "TempFiles", pSelDoc.FileName);

                arrBytes = m_ZipDati.Value.Decompress(arrBytes, lunghezzaOriginaria);
            }


            var isEncrypted = true;
            if (isEncrypted)
            {
                arrBytes = m_Encryptor.Value.Decrypt(arrBytes, "diego1");

                var sampleOut = new System.Text.ASCIIEncoding().GetString(arrBytes.ToArray());
                
                using (var stream = File.Create(tempDir))
                {                    
                    stream.Write(arrBytes, 0, arrBytes.Length);
                    stream.Flush(true);
                }

            }
            else
                arrBytes = doc.Documento;


         
        }
      

    }//fC
}
